
import ControlScript from "../PublicScript/ControlScript";
import {dataName, emitType} from "./GameData_red_blue_man";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Money extends cc.Component {

    @property(cc.Label)
    moneyLabel: cc.Label = null;

    static moneyNum:number = 0;

    onLoad () {
        this.node.zIndex = 1000;
        cc.game.on(emitType.showMoney, this.showMoney, this);
        cc.game.on(emitType.animShowMoney, this.animShow, this);
    }

    start () {
        this.showMoney();
    }

    static addMoney(num){
        Money.moneyNum += parseInt(num);
        Money.saveMoney(Money.moneyNum);
        cc.game.emit(emitType.showMoney);
    }

    showMoney(){
        this.moneyLabel.string = Money.moneyNum + "";
    }

    static newPlay(){
        let money = ControlScript.loadData(dataName.money);
        if(money == null || money == undefined || money == ""){
            if(CC_PREVIEW){
                Money.moneyNum = 10000000;
            }else{
                Money.moneyNum = 0;
            }
        }else{
            Money.moneyNum = parseInt(JSON.parse(money));
        }
        console.log("Money.moneyNum:", Money.moneyNum);
        Money.saveMoney(Money.moneyNum);
        cc.game.emit(emitType.showMoney);
    }

    static usingMoney(num, callBack, callback2?){
        if(num <= this.moneyNum){
            this.moneyNum -= num;
            Money.saveMoney(this.moneyNum);
            cc.game.emit(emitType.showMoney);
            callBack();
        }else{
            if(callback2){
                callback2();
            }else{
                ControlScript.createToast("金币不足！");
            }
        }
    }

    onClick(){
        ControlScript.loadRes("Prefab/getMoney", (res)=>{
            let view = cc.instantiate(res);
            view.parent = cc.find("Canvas");
        })
    }

    static saveMoney(num){
        ControlScript.saveData(dataName.money, num)
    }

    //
    animShow(num, callback?){
        let coin = Math.round(num / 70);
        let moneySum = Money.moneyNum;
        Money.moneyNum += num;
        Money.saveMoney(Money.moneyNum);
        let func = ()=>{
            moneySum += coin;
            this.moneyLabel.string = moneySum + "";
            if(moneySum >= Money.moneyNum){
                this.moneyLabel.string = Money.moneyNum + "";
                if(callback){
                    callback();
                }
                this.unschedule(func);
            }
        };
        this.schedule(func, 0.01);
    }
    // update (dt) {}
}
